package com.sdp.wx.handleImpl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdp.core.bizc.utils.ApplicationContextUtils;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.BusinessContext;
import com.sdp.core.bizc.vo.Result;
import com.sdp.wx.db.wx_warehouse_info.entity.WxWarehouseInfo;
import com.sdp.wx.db.wx_warehouse_info.service.IWxWarehouseInfoService;
import com.sdp.wx.db.wx_warehouse_right.service.IWxWarehouseRightService;
import com.sdp.wx.db.wx_wz_inventory.entity.WxWzInventory;
import com.sdp.wx.db.wx_wz_inventory.service.IWxWzInventoryService;
import com.sdp.wx.db.wx_wz_inventory_detail.entity.WxWzInventoryDetail;
import com.sdp.wx.db.wx_wz_inventory_detail.service.IWxWzInventoryDetailService;
import com.sdp.wx.db.wx_wz_now_num.service.impl.WxWzNowNumServiceImpl;
import com.sdp.wx.handle.WzInOutPutHandle;
import com.sdp.wx.utils.CurrentLoginEmp;
import com.sdp.wx.utils.WxConstants;
import com.sdp.wx.view.WzNowNumView;

@Component
public class WzInventoryHandlerImpl extends WzInOutPutHandle{
	
	@Autowired
	private CurrentLoginEmp currentLoginEmp;
	
	@Autowired
	private IWxWarehouseInfoService iWxWarehouseInfoService;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;
	
	@Autowired
	private IWxWzInventoryService iWxWzInventoryService;
	
	@Autowired
	private IWxWzInventoryDetailService iWxWzInventoryDetailService;
	
	@Autowired
	private WxWzNowNumServiceImpl wxWzNowNumServiceImpl;
	
	@Autowired
	private IWxWarehouseRightService iWxWarehouseRightService;

	@Override
	public BusinessContext execute(BusinessContext businessContext) {
		
		String method = businessContext.get("method");
		if(StringUtils.isEmpty(method)) {
			businessContext.setSuccess(false);
			businessContext.setMessage("盘存操作出现错误");
			return businessContext;
		}
		
		if(WxConstants.盘存方法_初始化.getCode().equals(method)) {
			return ApplicationContextUtils.getBean(WzInventoryHandlerImpl.class).init(businessContext);
		}else if(WxConstants.盘存方法_完成.getCode().equals(method)) {
			return ApplicationContextUtils.getBean(WzInventoryHandlerImpl.class).finish(businessContext);
		}else if(WxConstants.盘存方法_完成调差.getCode().equals(method)) {
			return ApplicationContextUtils.getBean(WzInventoryHandlerImpl.class).handleDif(businessContext);
		}
		return businessContext;
	}

	@Transactional(rollbackFor=Exception.class)
	public BusinessContext init(BusinessContext businessContext) {
		
		JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
		if(emp==null) {
			businessContext.setSuccess(false);
			businessContext.setMessage("请先登录");
			return businessContext;
		}
		WxWzInventory wzInventory = businessContext.get(WxWzInventory.class);
		
		//查看此仓库是否可用
		WxWarehouseInfo warehouseInfo = iWxWarehouseInfoService.queryWxWarehouseInfoByCode(wzInventory.getWarehouseCode());
		if(warehouseInfo==null || WxConstants.否.getCode().equals(warehouseInfo.getIsUse())) {
			businessContext.setMessage("此仓库已停用，不能盘存");
			businessContext.setSuccess(false);
			return businessContext;
		}
		
		//是否在锁定状态，锁定状态表示此仓库正在盘存
		if(WxConstants.是.getCode().equals(warehouseInfo.getIsLock())) {
			businessContext.setMessage("此仓库整在盘存中，请勿重复盘存");
			businessContext.setSuccess(false);
			return businessContext;
		}
		
		//是否有盘存权限
		boolean haveRight = iWxWarehouseRightService.isHaveRight(emp.getString("empNo"), wzInventory.getWarehouseCode(),WxConstants.库管权限_盘存.getCode());
		if(!haveRight) {
			businessContext.setMessage("您没有此仓库的盘存权限");
			businessContext.setSuccess(false);
			return businessContext;
		}
		
		Result<?> r = uniqueCheckTools.isUniqueSingle(iWxWzInventoryService, WxWzInventory.class, new String[] {"inventoryName"}, "keyId", wzInventory, null, false);
		if(r==null || !r.isSuccess()) {
			businessContext.setSuccess(false);
			businessContext.setMessage("盘存名称不能重复");
			return businessContext;
		}
		
		
		wzInventory.setOrgNo(emp.getString("orgNo"));
		wzInventory.setOpName(emp.getString("empName"));
		wzInventory.setOpNo(emp.getString("empNo"));
		wzInventory.setCreateTime(LocalDateTime.now());
		wzInventory.setInventoryTime(LocalDateTime.now());
		wzInventory.setInventoryState(WxConstants.盘存单盘点状态.getCode());
		wzInventory.setHandleState(WxConstants.否.getCode());
		
		List<WxWzInventoryDetail> wzInventoryDetailList = new ArrayList<WxWzInventoryDetail>();
		WxWzInventoryDetail wzInventoryDetail = null;
		
		QueryWrapper<WzNowNumView> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("b.warehouse_code", wzInventory.getWarehouseCode());
		List<WzNowNumView> wzNowNumList = wxWzNowNumServiceImpl.viewList(queryWrapper);
		if(wzNowNumList==null || wzNowNumList.size()==0) {
			businessContext.setSuccess(false);
			businessContext.setMessage("此仓库没有器材信息，无法盘存");
			return businessContext;
		}
		
		iWxWzInventoryService.save(wzInventory);
		for(WzNowNumView wz : wzNowNumList) {
			wzInventoryDetail = new WxWzInventoryDetail();
			wzInventoryDetail.setInventoryId(wzInventory.getKeyId());
			wzInventoryDetail.setWzNo(wz.getWzNo());
			wzInventoryDetail.setWzName(wz.getWzName());
			wzInventoryDetail.setNowNum(wz.getNowNum());
			wzInventoryDetail.setRealNum(wz.getNowNum());
			wzInventoryDetailList.add(wzInventoryDetail);
		}

		iWxWzInventoryDetailService.saveBatch(wzInventoryDetailList);
		
		//仓库锁定
		warehouseInfo.setIsLock(WxConstants.是.getCode());
		iWxWarehouseInfoService.updateById(warehouseInfo);

		return businessContext;
	}
	
	@Transactional(rollbackFor=Exception.class)
	public BusinessContext finish(BusinessContext businessContext) {
		String keyId = businessContext.get("keyId");
		if(StringUtils.isEmpty(keyId)) {
			businessContext.setMessage("盘存单信息不存在");
			businessContext.setSuccess(false);
			return businessContext;
		}
		WxWzInventory wzInventory = iWxWzInventoryService.getById(keyId);
		if(StringUtils.isEmpty(wzInventory)) {
			businessContext.setMessage("盘存单信息不存在");
			businessContext.setSuccess(false);
			return businessContext;
		}
		wzInventory.setInventoryState(WxConstants.盘存单已完成状态.getCode());
		
		WxWarehouseInfo warehouseInfo = iWxWarehouseInfoService.queryWxWarehouseInfoByCode(wzInventory.getWarehouseCode());
		if(warehouseInfo!=null) {
			warehouseInfo.setIsLock(WxConstants.否.getCode());
		}
		
		List<WxWzInventoryDetail> wzList = iWxWzInventoryDetailService.queryWzInventoryDetailByInventoryId(keyId);
		for(WxWzInventoryDetail wz : wzList) {
			if(wz.getNowNum().compareTo(wz.getRealNum())==0) {
				wz.setInventoryRes("盘平0");
				wz.setInventoryState(WxConstants.商品盘平状态.getCode());
				wz.setInventoryDif(BigDecimal.ZERO);
			}else if(wz.getRealNum().compareTo(wz.getNowNum())>0) {
				wz.setInventoryRes("盘盈"+wz.getRealNum().subtract(wz.getNowNum()));
				wz.setInventoryState(WxConstants.商品盘盈状态.getCode());
				wz.setInventoryDif(wz.getRealNum().subtract(wz.getNowNum()));
			}else if(wz.getRealNum().compareTo(wz.getNowNum())<0) {
				wz.setInventoryRes("盘亏"+wz.getRealNum().subtract(wz.getNowNum()));
				wz.setInventoryState(WxConstants.商品盘亏状态.getCode());
				wz.setInventoryDif(wz.getNowNum().subtract(wz.getRealNum()));
			}
		}

		iWxWarehouseInfoService.updateById(warehouseInfo);
		iWxWzInventoryService.updateById(wzInventory);
		iWxWzInventoryDetailService.updateBatchById(wzList);
		businessContext.put(WxWzInventory.class, wzInventory);
		
		return businessContext;
	}
	
	@Transactional(rollbackFor=Exception.class)
	public BusinessContext handleDif(BusinessContext businessContext) {
		String keyId = businessContext.get("keyId");
		WxWzInventory wzInventory = iWxWzInventoryService.getById(keyId);
		if(wzInventory!=null) {
			wzInventory.setHandleState(WxConstants.是.getCode());
		}
		iWxWzInventoryService.updateById(wzInventory);
		businessContext.put(WxWzInventory.class, wzInventory);
		return businessContext;
	}
}
